import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken} from '@/utils/auth'
import cript from '@/utils/encript.js'
import {clientname} from '@/settings';
import router from '@/router'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL: baseURL,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 300000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
	    config.headers["version"] = '1.0.1'
	    config.headers["clientname"] = clientname
      config.headers['Authorization'] = 'token ' + getToken()
      if(config.method == 'get'){
        if(store.getters.userModel.lessee){
          config.params = config.params?config.params:{}
          if(!config.params.lessee){
            config.params['lessee'] = store.getters.userModel.lessee
          }
        }
      }else if(config.method == 'post'){
        if(store.getters.userModel.lessee){
          config.data = config.data?config.data:{}
          if(!config.data.lessee){
            config.data['lessee'] = store.getters.userModel.lessee
          }
        }
      }
    }
    // console.log('-----------request', config)
    return cript.encript(config)
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
var flag = 0
// res interceptor
service.interceptors.response.use(
  res => {
    flag = 0
    // 解密
    if(res.data.data){
      res.data.data = cript.decript(res)
    }
    // if(res.config.data){
    //   res.config.data = cript.decript(res.config)
    // }
    // 限制只有lessee==1的时候才允许打印日志
    var lessee=null
    if(res.config.method == 'get' && res.config.params){
      lessee = res.config.params.lessee
    }else if(res.config.method == 'post' && res.config.data){
      lessee = res.config.data.lessee
    }
    if(store.getters.role=='admin' || store.getters.userModel.lessee==1 || localStorage.getItem('changeLesseeStatus')=='Y'){
      console.log('\n\n-----received request ' + res.config.method + ' ' + res.config.url)
      console.log('res:', res)
      console.log('-----end---------------------\n\n')
    }
   
    
    // if the custom code is not 20000, it is judged as an error.
    if(res.data.code == 8888){
      Message({
        message: res.data.message,
        duration: 5 * 1000
      })
    }else{
      return res
    }
  },
  error => {
    console.log('err---' + flag, error) // for debug
    if(error.message.indexOf('401') != -1){
      if(flag == 0){
        store.commit('SET_TOKEN', '')
        store.commit('SET_ROLES', [])
        store.commit('SET_PERMISSIONS', [])
        removeToken()
        router.push(`/login`)
        flag = 1
      }
    }else{
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
